/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: OtcOrderPresenter.java
 *   @Date: 19-1-25 下午2:39
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.otc.presenter;

import android.os.Bundle;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.bhex.app.base.AppUI;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BaseFragmentPresenter;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.sdk.otc.OtcConstant;
import io.bhex.sdk.otc.OtcOrderApi;
import io.bhex.sdk.otc.bean.OrderHistoryResponse;
import io.bhex.sdk.otc.bean.OrderPendingListResponse;
import io.bhex.sdk.otc.bean.OtcOrderInfoResponse;

public class OtcOrderPresenter extends BaseFragmentPresenter<OtcOrderPresenter.OtcOrderUI> {
    private String orderStatus="";
    private Timer timer;
    private TimerTask timerTask;
    private int page=1;
    private int pageSize=OtcConstant.PAGE_LIMIT;
    private List<OtcOrderInfoResponse> currentHistoryData = new ArrayList<>();
    private boolean isOrderProcessing;

    public void loadMore() {
        if (!TextUtils.isEmpty(orderStatus)&&!isOrderProcessing) {
            getOrders(true,orderStatus);
        }
    }

    public void refreshOrders() {
        if (!TextUtils.isEmpty(orderStatus)) {
            getOrders(false,orderStatus);
        }
    }

    public boolean getIsNeedLoadMore() {
        return !isOrderProcessing;
    }

    public interface OtcOrderUI extends AppUI{
        void loadMoreComplete();

        void loadMoreFailed();

        void loadEnd();

        void showOrderList(List<OtcOrderInfoResponse> datas);
    }

    @Override
    public void onUIReady(BaseCoreActivity activity, OtcOrderUI ui) {
        super.onUIReady(activity, ui);
        Bundle arguments = getFragment().getArguments();
        if (arguments != null) {
            orderStatus = arguments.getString("orderStatus");
            isOrderProcessing = orderStatus.equals("0");
            getOrders(false,orderStatus);
        }
    }

    @Override
    public void onVisibleChanged(boolean visible) {
        super.onVisibleChanged(visible);
        if (isOrderProcessing) {
            //当前订单需要定时刷新
            if (visible) {
                startTimer();
            }else{
                stopTimer();
            }
        }
    }


    private void startTimer() {
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(orderStatus)) {
                    getOrders(true,orderStatus);
                }
            }
        };
        timer.schedule(timerTask,OtcConstant.TIMER_DELAY_SHORT,OtcConstant.TIMER_PERIOD);

    }


    private void stopTimer() {
        if (timerTask!=null){
            timerTask.cancel();
        }
        if (timer != null) {
            timer.cancel();
        }
    }

    /**
     * 获取法币订单列表
     * @param isAutoLoad
     * @param orderStatus
     */
    public void getOrders(final boolean isAutoLoad, String orderStatus) {
        if (orderStatus.equals("0")) {
            //获取OTC当前进行中的订单
            OtcOrderApi.getOrderPendingList(new SimpleResponseListener<OrderPendingListResponse>(){
                @Override
                public void onBefore() {
                    super.onBefore();
                    if (!isAutoLoad) {
                        getUI().showProgressDialog("","");
                    }
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    if (!isAutoLoad) {
                        getUI().dismissProgressDialog();
                    }
                    getUI().loadMoreComplete();
                }

                @Override
                public void onSuccess(OrderPendingListResponse response) {
                    super.onSuccess(response);
                    if (CodeUtils.isSuccess(response,true)) {
                        List<OtcOrderInfoResponse> datas = response.getArray();
                        getUI().showOrderList(datas);
                        getUI().loadMoreComplete();
                    }else{
                        getUI().loadMoreComplete();
                    }
                }

                @Override
                public void onError(Throwable error) {
                    super.onError(error);
                }
            });
        }else{
            if (!isAutoLoad) {
                page = 1;
                pageSize = OtcConstant.PAGE_LIMIT;
            }
            OtcOrderApi.getOrderList(page,pageSize,new SimpleResponseListener<OrderHistoryResponse>(){
                @Override
                public void onBefore() {
                    super.onBefore();
                    if (!isAutoLoad) {
                        getUI().showProgressDialog("","");
                    }
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    if (!isAutoLoad) {
                        getUI().dismissProgressDialog();
                    }
                    getUI().loadMoreComplete();
                }

                @Override
                public void onSuccess(OrderHistoryResponse response) {
                    super.onSuccess(response);
                    if (CodeUtils.isSuccess(response,true)) {
                        List<OtcOrderInfoResponse> datas = response.getItems();
                        if (datas != null) {
                            page++;
                            if (isAutoLoad) {
                                currentHistoryData.addAll(datas);
                            }else{
                                currentHistoryData = datas;
                            }
                            getUI().showOrderList(currentHistoryData);
                            if (datas.size()< pageSize) {
                                getUI().loadEnd();
                            }else{
                                getUI().loadMoreComplete();
                            }
                        }else{
                            getUI().loadMoreComplete();
                        }
                    }else{
                        getUI().loadMoreFailed();
                    }
                }

                @Override
                public void onError(Throwable error) {
                    super.onError(error);
                }
            });
        }

    }
}
